package com.masiyi.parse;

import com.alibaba.druid.pool.DruidDataSource;
import com.masiyi.entity.Configuration;
import com.masiyi.io.Resources;
import lombok.SneakyThrows;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.sql.DataSource;
import javax.xml.parsers.SAXParser;
import java.io.InputStream;
import java.util.List;

/**
 * @Author：掉头发的王富贵
 * @Package：com.masiyi.parse
 * @Project：my-mybatis
 * @name：ConfigParse
 * @Date：2023/11/9 22:53
 * 作用：放置总配置的信息
 */
public class ConfigParse {

    private Configuration configuration;

    public ConfigParse() {
        this.configuration = new Configuration();
    }

    /**
     * 解析Configuration对象
     *
     * @param inputStream
     * @return
     */
    @SneakyThrows
    public Configuration parse(InputStream inputStream) {
        //读取输入流的文件信息，里面存储的即是myMybatisConfig.xml里面全部的内容
        Document document = new SAXReader().read(inputStream);
        //获取最上面的节点，即<configuration>
        Element configurationElement = document.getRootElement();

        //获取dataSource
        Element dataSource = configurationElement.element("dataSource");
        List<Element> property = dataSource.elements("property");

        DruidDataSource druidDataSource = new DruidDataSource();
        for (Element element : property) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            switch (name) {
                case "driverClassName":
                    druidDataSource.setDriverClassName(value);
                    break;
                case "url":
                    druidDataSource.setUrl(value);
                    break;
                case "username":
                    druidDataSource.setUsername(value);
                    break;
                case "password":
                    druidDataSource.setPassword(value);
                    break;
                default:
            }
        }
        configuration.setDataSource(druidDataSource);


        //获取mappers
        Element mappers = configurationElement.element("mappers");
        List<Element> mapper = mappers.elements("mapper");

        for (Element element : mapper) {
            MapperParse mapperParse = new MapperParse();
            String resourcePath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(resourcePath);
            mapperParse.parse(resourceAsStream, configuration);
        }
        return configuration;
    }
}
